<template>
  <div>
    <Card class="warp-card" dis-hover>
      <vxe-grid
        resizable
        border
        show-overflow
        highlight-hover-row
        row-id="id"
        :loading="loading"
        :form-config="tableForm"
        :toolbar="tableToolbar"
        :data="tableData"
        :columns="tableColumn"
        :export-config="{remote: true, exportMethod, types: ['csv'], modes: ['current', 'all']}"
        @form-submit="findList"
        @toolbar-button-click="buttonClick"
      >
      </vxe-grid>
      <Page
        :current="pageParam.pageNum"
        :page-size="pageParam.pageSize"
        :page-size-opts="[10, 20, 30, 50, 100]"
        :total="pageParam.total"
        @on-change="changePage"
        @on-page-size-change="changePageSize"
        show-elevator
        show-sizer
        show-total
        style="margin:24px 0;text-align:right;"
      ></Page>
    </Card>

    <!--ContactTableDetail 角色详情 start-->
    <ContactTableDetail ref="ContactTableDetail"></ContactTableDetail>
    <!--ContactTableDetail 角色详情 end-->

    <ContactTableAdd ref="ContactTableAdd" @addSuccess="findList"></ContactTableAdd>>
  </div>
  
</template>

<script>
import { contactApi } from '@/api/contact.js';
import ContactTableDetail from './components/contact-table-detail.vue'
import ContactTableAdd from './components/contact-table-add'
export default {
  name: 'ContactList',
  components: {
    ContactTableDetail,
    ContactTableAdd
  },
  props: {},
  data() {
    return {
      loading: false,
      pageParam: {
        total: 0, // 数据量
        pageNum: 1,
        pageSize: 10
      },
      buttonsPrivles: {
        
      },
      // column
      tableColumn: [
        {
          type:'seq',
          width: '50'
        },
        {
          title: '姓名',
          field: 'name'
        },
        {
          title: '邮箱',
          field: 'email'
        },
        {
          title: '助记码',
          field: 'mnemonicCode'
        },
        {
          title: '手机号',
          field: 'mobilePhone'
        },
        {
          title: '操作',
          field: 'action',
          width: 160,
          align: 'center',
          className: 'action-hide',
          slots: {
            default: ({row}, h) => {
              return this.$tableAction(h, [
                {
                  title: '详情',
                  action: () => {
                    this.getDetail(row);
                  }
                },
                {
                  title: '编辑',
                  directives: [
                    {
                      name: 'privilege',
                      value: 'contact-update'
                    }
                  ],
                  action: () => {
                    this.editEvent(row);
                  }
                },
                {
                  title: '删除',
                  directives: [
                    {
                      name: 'privilege',
                      value: 'contact-delete'
                    }
                  ],
                  action: () => {
                    this.deleteContact(row);
                  }
                }
              ]);
            }
          }
        }
      ],
      // search form
      tableForm: {
        titleWidth: 60,
        titleAlign: 'right',
        data: {
          searchCount: true,
          name: '',
          email: '',
          mobilePhone: '',
          mnemonicCode: ''
        },
        items: [
          { field: 'name', title: '姓名', span: 6, titlePrefix: { message: '', icon: 'fa fa-exclamation-circle' }, itemRender: { name: '$input', props: { placeholder: '请输入名称' } } },
          { field: 'email', title: '邮箱', span: 6, itemRender: { name: '$input', props: { placeholder: '请输入邮箱' } } },
          { field: 'mobilePhone', title: '手机号', span: 6, itemRender: { name: '$input', props: { placeholder: '请输入手机号' } } },
          { field: 'mnemonicCode', title: '助记码', span: 6, folding: true, titleSuffix: { message: '注意，必填信息！', icon: 'fa fa-info-circle' }, itemRender: { name: '$input', props: { placeholder: '请输入助记码' } } },
          { span: 24, align: 'center', collapseNode: true, itemRender: { name: '$buttons', children: [{ props: { type: 'submit', content: '查询', status: 'primary' } }, { props: { type: 'reset', content: '重置' } }] } }
        ]
      },
      // 按钮
      tableToolbar: {
        id: 'full_edit_1',
        export: true,
        custom: true,
        buttons: [
          { code: 'insert_code', name: '新增', icon: 'fa fa-plus', visible: true }
        ]
      },
      // table数据
      tableData: []
    };
  },
  computed: {},
  watch: {},
  filters: {},
  created() {
    this.findList();
  },
  methods: {
    // 更改分页查询条数
    changePageSize(pageSize) {
      this.pageParam.pageNum = 1;
      this.pageParam.pageSize = pageSize;
      this.findList();
    },
    // 页码改变
    changePage(pageNum) {
      this.pageParam.pageNum = pageNum;
      this.findList();
    },
    // 获取数据列表
    findList() {
      this.loading = true;
      let queryParams = Object.assign(this.pageParam, this.tableForm.data);
      contactApi.getContactList(queryParams).then((res) => {
        this.loading = false;
        this.tableData = res.data.list;
        this.pageParam.total = res.data.total;
        if (res.data.pages < this.pageParam.pageNum) {
          this.pageParam.pageNum = res.data.pages;
        }
      }).catch(error => {
        this.loading = false;
        console.log(error);
      });
    },
    // 新增
    insertEvent() {
      this.$refs['ContactTableAdd'].showModal();
    },
    editEvent(row) {
        console.log(row);
        this.$refs['ContactTableAdd'].showModal(row);
    },
    // 删除确定
    async deleteSure(delId) {
      this.loading = true;
      let res = await contactApi.deleteContact(delId);
      this.$Message.success('删除成功');
      this.loading = false;
      this.findList();
    },
    // 删除操作
    deleteContact(row) {
      this.$Modal.confirm({
        title: '友情提醒',
        content: '确定要删除吗？',
        onOk: () => {
          this.deleteSure(row.id);
        }
      });
    },
    // 详情
    async getDetail(row) {
      this.loading = true;
      let res = await contactApi.getDetail(row.id);
      this.loading = false;
      this.$refs['ContactTableDetail'].showModal(res.data);
    },
    buttonClick({code}, event) {
      switch (code) {
        case 'insert_code': 
          this.insertEvent();
      }
    },
    // importMethod ({ file }) {
    //   const formBody = new FormData()
    //   formBody.append('file', file)
    //   return XEAjax.post('https://api.xuliangzhan.com:10443/api/user/import', formBody).then(data => {
    //     this.$XModal.message({ message: `成功导入 ${data.result.insertRows} 条记录！`, status: 'success' })
    //     // 导入完成，刷新表格
    //     this.$refs.xGrid.commitProxy('query')
    //   }).catch(() => {
    //     this.$XModal.message({ message: '导入失败，请检查数据是否正确！', status: 'error' })
    //   })
    // },
    exportMethod ({ options }) {
      console.log(options);
      // const proxyInfo = this.$refs.xGrid.getProxyInfo()
      // const body = {
      //   filename: options.filename,
      //   sheetName: options.sheetName,
      //   isHeader: options.isHeader,
      //   original: options.original,
      //   mode: options.mode,
      //   pager: proxyInfo.pager,
      //   ids: options.mode === 'selected' ? options.data.map(item => item.id) : [],
      //   fields: options.columns.map(column => {
      //     return {
      //       field: column.property,
      //       title: column.title
      //     }
      //   })
      // }
      // 开始服务端导出
      // return XEAjax.post('https://api.xuliangzhan.com:10443/api/user/export', body).then(data => {
      //   if (data.id) {
      //     this.$XModal.message({ message: '导出成功，开始下载', status: 'success' })
      //     // 读取路径，开始下载
      //     location.href = `https://api.xuliangzhan.com:10443/api/download/${data.id}`
      //   }
      // }).catch(() => {
      //   this.$XModal.message({ message: '导出失败！', status: 'error' })
      // })
      return contactApi.export().then(response => {
        console.log(response);
      }).catch(error => {
        this.$XModal.message({ message: '导出失败！', status: 'error' })
      });
    }
  }
};
</script>
